package com.rem.photoablum.service;

import com.rem.photoablum.dao.AlbumDao;
import com.rem.photoablum.dao.PhotoDao;
import com.rem.photoablum.model.Album;
import com.rem.photoablum.utils.PhotoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AlbumService {
    @Autowired
    private AlbumDao albumDao;
    @Autowired
    private  PhotoUtil photoUtil;
    @Autowired
    private PhotoDao photoDao;

    public Album addAlbum(Album album){
        //jpa有问题，主键自增不知道为啥没用，用随机数代替id，有十万分之一率插入失败
        long aid = (long) (Math.random()*100000+1);
        String path = photoUtil.createAlbum(album);
        album.setPath(path);
//        System.out.println("AlbumService-->:"+ album.toString());
        album.setAid(aid);
        albumDao.addAlbum(album.getAid(),album.getPid(),album.getAlbumName(),album.getAlbumDesc(),album.getTopic(),album.getPath());
        return album;
    }

    public void deleteByAid(Long aid){
        albumDao.deleteAllByAid(aid);
    }


    public Integer updateByAid(Album album){
        return albumDao.updateByAid(album.getAlbumName(),album.getAlbumDesc(),album.getTopic(),album.getAid());
    }

    public List<Album> findAll(){
        return albumDao.findAll();
    }

    public List<Album> findAlbumByPid(Integer pid){
        return albumDao.findAlbumByPid(pid);
    }

    public Album findAlbumsByPidAndAlbumName(Integer pid,String album){
        return albumDao.findAlbumsByPidAndAlbumName(pid,album);
    }

    public String deleteAlbum(Long aid){
        Album albumByAid = albumDao.findAlbumByAid(aid);
        String path = albumByAid.getPath();
        photoUtil.deleteAlbum(path);
        albumDao.deleteAllByAid(aid);
        photoDao.deleteAllByAid(aid);
        return "ok";
    }

    public Album findAlbumsByAlbumName(String albumName) {
        return albumDao.findByAlbumName(albumName);
    }
}
